#include "HufArc.h"

unsigned char * HufTreeToStr (__HufTree * head, size_t * ubits,size_t * len)
{
	int i = 0;
	size_t str_size = 0;
	int m = 0;
	int n = 1;
	unsigned int count = 0;
	int count_arr = 1;
	unsigned char * hufStr = NULL;
	__HufTree ** arr = NULL;
	arr = makeArrHufTree (arr,head,&count_arr);
	while (arr[i])
	{
		if (arr[i]->flag)
			count ++;
		else
			count +=9;
		i++;
	}
	str_size = count / 8;
	if (count % 8)
		str_size ++;
	ubits[0]=8-(count % 8);
	hufStr = (unsigned char*) calloc (str_size,sizeof(char));
	i = 0;
	m = 0;
	n = 0;
	len[0] = str_size;
	while (i<str_size)
	{
		if (arr[m])
		{
				if (arr[m]->flag)
				{
					if (n!=7)
					{
						hufStr[i]<<=1;
						n++;
					}
					else
					{
						n = 0;
						i++;
					}
					m++;
				} else
				{
					hufStr[i] |= 1;
					if (n != 7)
					{
						hufStr[i]<<=1;
						n++;
					} else
					{
						n = 0;
						i++;
					}
					if (n == 0)
					{
						hufStr[i] = arr[m]->alpha;
						m++;
						i++;
					} else
					{
						hufStr[i] <<= (7-n);
						hufStr[i] |= (arr[m]->alpha>>n);
						i++;
						hufStr[i] = (arr[m]->alpha << (8-n));
						hufStr[i] >>= (7-n);
						m++;
					}
				}
		} else
		{
			i++;
			}
	}
	hufStr[i-1] <<=(ubits[0]-1);
	return hufStr;
}